﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Xml;
using System.Text.RegularExpressions;
using Gecko;

namespace OnlineMusic
{
    public partial class mainf : Form
    {
        int status = 1;
        int sh = 0, sm = 0, ss = 0;
        bool shutdown = false;

        public static Data data = null;
        public LrcForm lrcForm = null;

        public mainf()
        {
            Gecko.Xpcom.Initialize(Application.StartupPath + "\\xulrunner");
            //GeckoPreferences.Default["plugin.state.flash"] = 2;
            //GeckoPreferences.User["browser.xul.error_pages.enabled"] = true;
            //GeckoPreferences.User["media.navigator.enabled"] = true;
            //GeckoPreferences.User["media.navigator.permission.disabled"] = true;
            Gecko.LauncherDialog.Download += new EventHandler<Gecko.LauncherDialogEvent>(OnDownloadFile);
            InitializeComponent();
            data = new Data();
            if (!data.isReady())
            {
                data.init();
            }
            InitBtPanel();
        }

        private void initwB(object sender, EventArgs e)
        {
            //wb.Navigate("http://douban.fm");
            string lasturl = data.getLasturl();
            wB.EnableConsoleMessageNotfication();
            this.wB.ConsoleMessage += new System.EventHandler<Gecko.ConsoleMessageEventArgs>(this.wB_ConsoleMessage);
            //this.wB.JavascriptError += new Gecko.GeckoWebBrowser.JavascriptErrorEventHandler(this.wB_JavascriptError);
            if (lasturl.Equals(""))
                wB.Navigate("http://fm.mp3.baidu.com");
            else
                wB.Navigate(lasturl);
        }
        private void OnDownloadFile(object sender, LauncherDialogEvent e)
        {
            nsILocalFile objTarget = Xpcom.CreateInstance<nsILocalFile>("@mozilla.org/file/local;1");

            using (nsAString tmp = new nsAString(@Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\temp.tmp"))
            {
                objTarget.InitWithPath(tmp);
            }

            //Save file dialog
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "All files (*.*)|*.*";
            saveFileDialog1.FilterIndex = 2;
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.FileName = e.Filename;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                System.IO.Stream myStream;
                if ((myStream = saveFileDialog1.OpenFile()) != null)
                {
                    myStream.Close();
                    nsIURI source = IOService.CreateNsIUri(e.Url);
                    nsIURI dest = IOService.CreateNsIUri(new Uri(@saveFileDialog1.FileName).AbsoluteUri);
                    nsAStringBase t = (nsAStringBase)new nsAString(System.IO.Path.GetFileName(@saveFileDialog1.FileName));

                    nsIWebBrowserPersist persist = Xpcom.CreateInstance<nsIWebBrowserPersist>("@mozilla.org/embedding/browser/nsWebBrowserPersist;1");

                    nsITransfer nst = Xpcom.CreateInstance<nsITransfer>("@mozilla.org/transfer;1");
                    nst.Init(source, dest, t, e.Mime, 0, null, persist, false);

                    if (nst != null)
                    {
                        persist.SetPersistFlagsAttribute(2 | 32 | 16384);
                        persist.SetProgressListenerAttribute((nsIWebProgressListener)nst);
                        //persist.SaveURI(source, null, null, (uint)Gecko.nsIHttpChannelConsts.REFERRER_POLICY_NO_REFERRER, null, null, (nsISupports)dest, null);
                        persist.SaveURI(source, null, null, null, null, (nsISupports)dest, null);
                    }
                }
            }
        }

        private void bgo_Click(object sender, EventArgs e)
        {
            //  if (urlbox.Text != "")
            {
                wB.Navigate(urlbox.Text);
            }
        }

        private void noty_Click(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                this.Visible = true;
                this.Focus();
                if (status == 0)
                    WindowState = FormWindowState.Normal;
                else
                    WindowState = FormWindowState.Maximized;
                this.noty.Visible = false;
                this.Activate();
            }
        }

        private void mainf_SizeChanged(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Normal)
                status = 0;
            else if (WindowState == FormWindowState.Maximized)
                status = 1;
            else
            {
                this.Visible = false;
                this.noty.Visible = true;
            }
        }

        private void changetitle(object sender, EventArgs e)
        {
            this.Text = wB.DocumentTitle;
            this.noty.Text = wB.DocumentTitle;
            this.urlbox.Text = wB.Url.ToString();
            data.setLasturl(wB.Url.ToString());
            if (lrcForm != null)
            {
                try
                {
                    System.Threading.Thread.Sleep(1000);
                    Regex reg = new Regex("^[^\\-]+\\s?\\-\\s?[^\\-\\s]+(\\s|\\-|\\|)");
                    Match match = reg.Match(wB.DocumentTitle);
                    if (match.Success)
                    {
                        bool iskugou = wB.Url.Host.Equals("web.kugou.com");
                        lrcForm.ShowLrc(match.Value.Substring(0, match.Value.Length - 1), iskugou);
                    }
                }
                finally
                {
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            SetForm set = new SetForm(this);
            set.SetStatus(this.t.Enabled, this.sh, this.sm, this.ss, this.shutdown);
            set.ShowDialog(this.Owner);
        }

        public void SetTimeTask(bool enable, int h, int m, int s, bool shutdown)
        {
            if (enable)
            {
                this.sh = h;
                this.sm = m;
                this.ss = s;
                this.shutdown = shutdown;
            }
            this.t.Enabled = enable;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            TimeSpan t = new TimeSpan(this.sh, this.sm, this.ss);
            double diff = DateTime.Now.TimeOfDay.Subtract(t).TotalSeconds;
            if (Math.Abs(diff) < 1)
            {
                if (this.shutdown)
                    ShutDown.DoExitWin(ShutDown.EWX_SHUTDOWN);
                this.Close();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.TopMost = !this.TopMost;
        }

        private void InitBtPanel()
        {
            int x = 7;
            x = this.bt_set.Width + this.bt_top.Width + this.bt_fa.Width + this.bt_lrc.Width;
            foreach (XmlElement xmlelement in data.getFavoriteList())
            {
                Label plb = new Label();
                plb.Cursor = System.Windows.Forms.Cursors.Hand;
                plb.Size = new System.Drawing.Size(77, 22);
                plb.Location = new Point(x, 1);
                plb.Image = global::OnlineMusic.Properties.Resources.bg_label1;
                plb.Text = xmlelement["title"].InnerText;
                plb.Padding = new Padding(5);
                this.tt.SetToolTip(plb, xmlelement["title"].InnerText);
                x += plb.Width;
                plb.Click += new EventHandler(plb_Click);
                plb.ContextMenuStrip = this.fcm;
                this.btpanel.Controls.Add(plb);

            }
        }

        void plb_Click(object sender, EventArgs e)
        {
            Label lb = (Label)sender;
            OpenFavorite(lb.Text);
        }

        private void OpenFavorite(string title)
        {
            this.wB.Navigate(data.getFavoriteUrl(title));
        }

        private void bt_fa_Click(object sender, EventArgs e)
        {
            Favorite fa = new Favorite();
            fa.Controls["tb_title"].Text = this.wB.DocumentTitle;
            fa.Controls["tb_url"].Text = this.wB.Url.ToString();
            fa.mf = this;
            fa.data = data;
            fa.ShowDialog(this.Owner);
        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem tsmi = (ToolStripMenuItem)sender;
            ContextMenuStrip cms = (ContextMenuStrip)tsmi.GetCurrentParent();
            Label lb = (Label)cms.SourceControl;
            OpenFavorite(lb.Text);
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem tsmi = (ToolStripMenuItem)sender;
            ContextMenuStrip cms = (ContextMenuStrip)tsmi.GetCurrentParent();
            Label lb = (Label)cms.SourceControl;
            string title = lb.Text;
            data.deleteFavorite(title);
            ReInitBtPanel();
        }

        public delegate void InvokeShowMsg();

        public void ReInitBtPanel()
        {
            if (this.btpanel.InvokeRequired)
            {
                InvokeShowMsg ism = new InvokeShowMsg(ReInitBtPanel);
                this.Invoke(ism);
            }
            else
            {
                while (this.btpanel.Controls.Count > 0)
                    this.btpanel.Controls.RemoveAt(0);
                this.btpanel.Controls.Add(this.bt_fa);
                this.btpanel.Controls.Add(this.bt_top);
                this.btpanel.Controls.Add(this.bt_set);
                this.btpanel.Controls.Add(this.bt_lrc);
                InitBtPanel();
            }
        }


        private void wB_CreateWindow(object sender, Gecko.GeckoCreateWindowEventArgs e)
        {
            e.WebBrowser = new Gecko.GeckoWebBrowser();
            newWindow nw = new newWindow();
            nw.Show();
            nw.ShowWB(e.WebBrowser);
        }

        private void bt_lrc_Click(object sender, EventArgs e)
        {
            if (lrcForm == null)
            {
                lrcForm = new LrcForm();
                lrcForm.Show();
                this.bt_lrc.Text = "歌词(开)";
            }
            else
            {
                lrcForm.Close();
                lrcForm = null;
                this.bt_lrc.Text = "歌词(关)";
            }
        }

        private void wB_ConsoleMessage(object sender, Gecko.ConsoleMessageEventArgs e)
        {
            if (String.IsNullOrEmpty(e.Message))
                return;
            if (e.Message.StartsWith("[JavaScript Warning:"))
                return;
            Console.WriteLine(e.Message);
        }

        private void wB_NSSError(object sender, Gecko.Events.GeckoNSSErrorEventArgs e)
        {

        }

    }
}
